import React,{ useEffect, useState, useRef } from "react";
import { FloatButton,Spin } from "antd"
import BlogCard from '../../components/blog-card'
import { useTableData } from '../../hooks/table/useTableData'
import { debounce } from 'lodash'
import './list.css'
const List = () => {
    const [total,setTotal] = useState(0)
    // const [isScrollBottom, setIsScrollBottom] = useState(false);
    const scrollContainerRef = useRef(null);
    const [ ajaxData, setAjaxData  ] = useState({
        page: 1,
        limit: 12,
        status: 1
    })
    const { loading, getTableData,tableData,noData} = useTableData({
        tableUrl: '/news/query',
        setTotal,
        ajaxData
    })
    const handleBottom = () => {
        if (scrollContainerRef.current) {
            scrollContainerRef.current.addEventListener('scroll', event =>{
                const { scrollTop, clientHeight, scrollHeight } = event.target;
                if(parseInt(scrollTop) + clientHeight === scrollHeight && !loading) {
                    setAjaxData({
                        ...ajaxData,
                        page: ajaxData.page + 1
                    })
                }
            })
        }
    }
    const debounceHandle = debounce(handleBottom, 1000)
    useEffect(() => {
        debounceHandle()
        !noData && getTableData(ajaxData)
    },[ajaxData])
    return (
            <div ref={scrollContainerRef} className= 'list-container'>
                <div className="list-content">
                    {
                        tableData.map(item => {
                            return <BlogCard key={item._id} item={item} />
                        })
                    }
                    <FloatButton.BackTop target={() => scrollContainerRef.current} visibilityHeight={100} title={'返回顶部'}  />
                </div>
                {loading && <div className="footer">
                    <Spin className="spin-container" spinning={loading}  size="large" />
                </div>}
            </div>
    )
}

export default List
